# 导包
from django.contrib.auth.backends import ModelBackend
import re
# 类继承
# 重写父类的函数
from apps.users.models import User


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # 区别手机号
        if re.match('^1[3456789]\d{9}$', username):
            user = User.objects.get(mobile=username)

        # 2.username
        else:
            user = User.objects.get(username=username)

        # 3.校验密码
        if user and user.check_password(password):
            return user


